﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Web.Core
{
    public class Cipher
    {
        public Cipher()
        { }

        public static string EncrytData(string original)
        {
            Encoding textConverter = Encoding.Default;
            RijndaelManaged myRijndael = new RijndaelManaged();
            byte[] encrypted;
            byte[] toEncrypt;

            //					K		.		U		.		T		e		l		e		c		o		m		_		2		5		3		8
            byte[] Key = { 0x4B, 0x2E, 0x55, 0x2E, 0x54, 0x65, 0x6C, 0x65, 0x63, 0x6F, 0x6D, 0x5F, 0x32, 0x35, 0x33, 0x38 };
            byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

            //Get an encryptor.
            ICryptoTransform encryptor = myRijndael.CreateEncryptor(Key, IV);

            //Encrypt the data.
            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

            //Convert the data to a byte array.
            toEncrypt = textConverter.GetBytes(original.Trim());

            //Write all data to the crypto stream and flush it.
            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            //Get encrypted array of bytes.
            encrypted = msEncrypt.ToArray();

            string encrytResult = Convert.ToBase64String(encrypted);
            return encrytResult;
        }

        public static string DecrytData(string inputData)
        {
            Encoding textConverter = Encoding.Default;
            RijndaelManaged myRijndael = new RijndaelManaged();

            byte[] fromEncrypt;
            byte[] encrypted = Convert.FromBase64String(inputData.Trim());

            //					K		.		U		.		T		e		l		e		c		o		m		_		2		5		3		8
            byte[] Key = { 0x4B, 0x2E, 0x55, 0x2E, 0x54, 0x65, 0x6C, 0x65, 0x63, 0x6F, 0x6D, 0x5F, 0x32, 0x35, 0x33, 0x38 };
            byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

            ICryptoTransform decryptor = myRijndael.CreateDecryptor(Key, IV);

            MemoryStream msDecrypt = new MemoryStream(encrypted);
            CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

            fromEncrypt = new byte[encrypted.Length];
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            string converData = textConverter.GetString(fromEncrypt);
            string[] output = converData.Split('\0');
            return output[0];
        }

    }
}